package tcp

import (
	"encoding/json"
	"errors"
	"github.com/sirupsen/logrus"
	"hcy-api/lib/id"
	"hcy-api/structs/base"
	"hcy-api/structs/enum"
	"hcy-api/structs/tables"
	"hcy-api/structs/vap"
	"time"
	dao2 "vap/module/dao"
)

func (c *Client) sayHi(in base.ClientResponse) (err error) {
	if in.ResultType != enum.SayHi {
		err = errors.New("消息处理方法不匹配")
		return
	}
	var (
		ah  tables.VapHost
		msg vap.AppHost
	)
	err = json.Unmarshal([]byte(in.Result), &msg)
	if err != nil {
		return
	}
	if c.Uid == "" {
		c.Uid = msg.Uid
		c.online(msg.Uid)
	}
	if ah, err = dao2.HostRepository.FindByHostUid(msg.Uid); err != nil {
		return err
	}
	if ah.Id == 0 {
		ah = c.VapHostTransformTable(msg)
		ah.Id = id.GetSnowId()
		ah.Origin = tables.AppHostOriginForClient
		ah.Status = tables.AppHostStatusActivated
		if err = dao2.HostRepository.CreateHost(&ah); err != nil {
			return
		}
	} else {
		// 检查主机信息，如果有变化就更新
		b := false
		if ah.Ip != msg.Ip {
			ah.Ip = msg.Ip
			b = true
		}
		if ah.Domain != msg.Domain {
			ah.Domain = msg.Domain
			b = true
		}
		if ah.OsCaption != msg.OsCaption {
			ah.OsCaption = msg.OsCaption
			b = true
		}
		if ah.Os != msg.Os {
			ah.Os = msg.Os
			b = true
		}
		if ah.BuildNumber != msg.BuildNumber {
			ah.BuildNumber = msg.BuildNumber
			b = true
		}
		if ah.Version != msg.Version {
			ah.Version = msg.Version
			b = true
		}
		if ah.RdpPort != msg.RdpPort {
			ah.RdpPort = msg.RdpPort
			b = true
		}
		if b {
			if err = dao2.HostRepository.UpdateHostById(&ah); err != nil {
				return
			}
		}
	}
	return
}

// saveAppList 保存应用信息
func (c *Client) saveAppList(in base.ClientResponse) (err error) {
	var (
		appAll []tables.VapAppInstall
		m      tables.VapHost
	)
	m, err = dao2.HostRepository.FindHostByHostUId(c.Uid)
	if err != nil {
		return
	}
	err = json.Unmarshal([]byte(in.Result), &appAll)
	if err = dao2.SessionRepository.DeleteAppInstallByHostId(m.Id); err != nil {
		return
	}
	for i := range appAll {
		appAll[i].Id = id.GetSnowId()
		appAll[i].HostId = m.Id
		appAll[i].CreatedAt = time.Now().Unix()
	}
	if len(appAll) > 0 {
		if err = dao2.SessionRepository.BatchInsertAppInstallList(appAll); err != nil {
			return
		}
	}
	return
}

// handleSessionChange 处理win会话变化
func (c *Client) handleSessionChange(in base.ClientResponse) (err error) {
	var (
		session tables.VapSession
		msg     vap.WinSessionChangeMsg
		m       tables.VapHost
	)
	m, err = dao2.HostRepository.FindHostByHostUId(c.Uid)
	if err != nil {
		return
	}
	if err = json.Unmarshal([]byte(in.Result), &msg); err != nil {
		logrus.Error(err)
		return
	}
	switch msg.WtsCode {
	case 1: // 本地连接
	case 2: // 本地断开
	case 3: // 远程连接
		logrus.Debugf("远程连接：%v", msg)
	case 4: // 远程断开，正常不会触发，因为go会一直握持ws
		//if session, err = dao.SessionRepository.FindByHostIdAndWinId(m.DeviceId, int64(in.WinSessionId)); err != nil {
		//	return
		//}
		//session.Message = "会话断开"
		//session.Status = tables.VaSessionStatusForWinBreak
		//session.HoldStatus = tables.VaSessionHoldForHolding
		//if err = dao.SessionRepository.UpdateById(&session); err != nil {
		//	return
		//}
	case 5: // 会话登录
		logrus.Debugf("会话登录：%v", msg)
	case 6: // 会话注销
		if session, err = dao2.SessionRepository.FindByHostIdAndWinId(m.Id, int64(msg.WinSessionId)); err != nil {
			return
		}
		if session.Id != 0 {
			session.Message = "会话注销"
			session.Status = tables.VaSessionHoldForHeld
			session.HoldStatus = tables.VaSessionStatusForWinDestroyed
			if err = dao2.SessionRepository.UpdateById(&session); err != nil {
				return
			}
		}
	default:
		logrus.Errorf("WM_QUERYENDSESSION：不知道具体含义的状态，需要排查：%v", in)
	}
	return
}

// VapHostTransformTable 结构体转换
func (c *Client) VapHostTransformTable(in vap.AppHost) (m tables.VapHost) {
	m.Uid = in.Uid
	m.HostName = in.HostName
	m.Mac = in.Mac
	m.Ip = in.Ip
	m.Domain = in.Domain
	m.Os = in.Os
	m.OsCaption = in.OsCaption
	m.PartOfDomain = in.PartOfDomain
	m.SystemType = in.SystemType
	m.BuildNumber = in.BuildNumber
	m.OsArchitecture = in.OsArchitecture
	m.Version = in.Version
	m.SerialNumber = in.SerialNumber
	m.RdpPort = in.RdpPort
	m.CpuInfo = in.CpuInfo
	return m
}
